package com.danjinwulian.mnp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.danjinwulian.common.core.domain.entity.IotDevice;
import com.danjinwulian.common.core.domain.entity.IotProduct;
import com.danjinwulian.common.core.domain.entity.IotTenant;
import com.danjinwulian.common.core.domain.entity.IotTenantPower;
import com.danjinwulian.iot.service.TencentIotService;
import com.tencentcloudapi.iotexplorer.v20190423.models.*;
import com.danjinwulian.common.constant.IoTConstants;
import com.danjinwulian.common.core.controller.BaseController;
import com.danjinwulian.common.core.domain.AjaxResult;
import com.danjinwulian.common.utils.StringUtils;
import com.danjinwulian.device.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 设备信息（小程序端调用接口）
 *
 * @author ken.h
 */
@RestController
@RequestMapping("/mnp/device")
public class DeviceController extends BaseController
{
    private final static Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    private IIotDeviceService deviceService;
    @Autowired
    private IIotProductService productService;
    @Autowired
    private IIotTenantService tenantService;
    @Autowired
    private IIotTenantPowerService tenantPowerService;
    @Autowired
    private TencentIotService tencentIotService;

    /**
     * 电路开关修改（10扫码开电 11远程通电 12自动通电 01远程断电 02强制断电 03人走断电）
     */
//    @PreAuthorize("@ss.hasPermi('device:device:edit')")
//    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeCircuitSwitch")
    public AjaxResult changeCircuitSwitch(@RequestBody IotDevice device)
    {
        IotProduct product = productService.selectProductById(device.getProductId());
        if (StringUtils.isNotNull(product)) {
            IotDevice existDevice = deviceService.selectDeviceByDeviceName(device.getDeviceName());
            if (StringUtils.isNotNull(existDevice)) {
                if (IoTConstants.DEVICE_ONLINE.equals(existDevice.getStatus())) {
                    try {
                        // 使用腾讯云物联网开发平台发布消息
                        Map message = new HashMap();
                        message.put("method", "circuit_switch_cmd");
                        message.put("value", device.getCircuitSwitch());

                        String topic = "$thing/down/property/" + existDevice.getProductId() + "/" + device.getDeviceName();
                        String payload = JSONObject.toJSONString(message);

                        logger.info("客户侧【" + device.getDeviceName() + "】下发【circuit_switch_cmd】消息：" + payload);

                        PublishMessageResponse response = tencentIotService.publishMessage(
                                product.getProductId(), device.getDeviceName(), topic, payload);

                        if (response.getRequestId() != null) {
                            logger.info("客户侧返回【circuit_switch_cmd】消息发送成功");

                            device.setUpdateBy(getUsername());
                            int flag = deviceService.updateCircuitSwitch(device);
                            if (flag > 0) {
                                // 新增住客用电对象
                                IotTenantPower tenantPower = new IotTenantPower();
                                tenantPower.setDeviceId(existDevice.getDeviceId());
                                tenantPower.setPowerType(device.getCircuitSwitch());

                                if (StringUtils.isNotEmpty(device.getUnionid())) {
                                    IotTenant tenant = tenantService.selectIotTenantByUnionid(device.getUnionid());
                                    if (StringUtils.isNotNull(tenant)) {
                                        tenantPower.setTenantId(tenant.getTenantId());
                                    }
                                }
                                tenantPower.setCreateBy(getUsername());
                                tenantPowerService.insertIotTenantPower(tenantPower);
                            }
                            return toAjax(flag);
                        } else {
                            return AjaxResult.error("下发指令失败，请联系管理员！" + JSON.toJSONString(response));
                        }
                    } catch (Exception e) {
                        return AjaxResult.error("下发指令失败，请联系管理员！" + e.getMessage());
                    }
                } else {
                    return AjaxResult.error("设备不在线！");
                }
            } else {
                return AjaxResult.error("设备不存在！");
            }
        } else {
            return AjaxResult.error("设备对应产品不存在！");
        }
    }

}